package com.example.allshengmedical.experimentrun.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.R.integer;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.allsheng.dataprocess.AutoBaseline;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.experimentnew.bean.FileBean;
import com.example.allshengmedical.experimentnew.bean.LayoutTableBean;
import com.example.allshengmedical.experimentnew.bean.MethodBean;
import com.example.allshengmedical.util.FileManagerUtil;
import com.example.allshengmedical.util.LogUtil;
import com.example.allshengmedical.util.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itboye.allshengmedical.sci.packet.resp.DetectLightIntensitTempRespPacket;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

public class ServiceMethodUtils {
	AmplifucationActivity amplifucationActivity;
	ArrayList<String> targetarrayList = new ArrayList<String>();
	ArrayList<String> DyesarrayList = new ArrayList<String>();
	ArrayList<String> ColorarrayList = new ArrayList<String>();
	ArrayList<Integer> indexArrayList = new ArrayList<Integer>();
	List<HashMap<String, Object>> dataSourceListBlock1 = new ArrayList<HashMap<String, Object>>();
	List<HashMap<String, Object>> dataSourceListBlock2 = new ArrayList<HashMap<String, Object>>();

	/**
	 * 
	 * @param appFilePath
	 *            路径名
	 * @param contextString
	 */
	public void getInfo(String appFilePath, StringBuffer contextString) {
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "") + "";

		String path = appFilePath + "/" + folderName;

		File file = new File(path + "/" + fileName);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				// System.out.println("line " + line + ": " + tempString);
				// Log.e("--", tempString);
				contextString.append(tempString);
				contextString.append(",");
				line++;
				SystemClock.sleep(1);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();

				} catch (IOException e1) {
				}
			}
		}

	}

	/********************************************************************************
	 * 功能：多通道荧光校准 形参： myarrArrayListIn为一个样品n个通道的荧光数据,
	 * arrayListCorrectionIn为校准参数（读取系统参数文件得到） int
	 * ichannelSlected,以二进制表示启用几通道数据，比如1表示只有1通道数据，2表示只有2通道数据，3表示12通道有数据
	 * 返回：校准过的数据getarrayListNormal
	 ********************************************************************************/
	// public ArrayList<String> getarrayListCorrection(ArrayList <String>
	// myarrArrayListIn, int ichannelSlected, ArrayList<ArrayList<String>>
	// arrayListCorrectionIn)//返回CtValue，错误返回0
	// {
	// return(myarrArrayListIn);
	// }
	//

	public void saveRawData2(
			HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList,
			AmplifucationDBHelper amplifucationDBHelper,
			RawDataTwoDBHelper rawDataDBHelper) {
		int ichannelSlected = Integer.parseInt(ichannelSlected(arrayList), 2);
		ArrayList<Float> lineArrayList = new ArrayList<Float>();
		int id = 0;
		// id = amplifucationDBHelper.queryID(amplifucationDBHelper.sqlDB(), i,
		// n,
		// j);
		for (int n = 1; n <= 4; n++) {
			for (int i = 0; i < 32; i++) {
				lineArrayList = amplifucationDBHelper.queryLine(i, n);

			}
		}
	}

	private String ichannelSlected(
			HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList) {
		String s = "0000";
		for (int channel = 1; channel <= 4; channel++) {

			if (arrayList.get(channel) == null) {
			} else {
				if (channel == 1) {
					s = s.substring(0, 3) + "1";
				}
				if (channel == 2) {
					s = s.substring(0, 2) + "1" + s.substring(3, 4);
				}
				if (channel == 3) {
					s = s.substring(0, 1) + "1" + s.substring(2, 4);
				}
				if (channel == 3) {
					s = "1" + s.substring(1, 4);
				}
			}

		}
		return s;
	}

	/**
	 * 保存扩增光强数据
	 * 
	 * @param isCircleEnd
	 *            是否循环结束
	 * @param arrayList
	 * @param appFilePath文件路径
	 */
	public synchronized void saveLightDate(final String appFilePath,
			final AmplifucationDBHelper amplifucationDBHelper,
			final StringBuffer contextString) {
		// TODO Auto-generated method stub
		saveRawdata(amplifucationDBHelper, appFilePath);
		saveAmpdata(amplifucationDBHelper, appFilePath, contextString);
		saveMuData(appFilePath, amplifucationDBHelper, contextString);
	}

	// public synchronized void saveLightDate(boolean isCircleEnd,
	// final HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList,
	// final String appFilePath,
	// final AmplifucationDBHelper amplifucationDBHelper,
	// final StringBuffer contextString) {
	// // Thread thread = new Thread(new Runnable() {
	// // @Override
	// // public void run() {
	// // // // TODO Auto-generated method stub
	// saveRawdata(arrayList, appFilePath);
	// saveAmpdata(arrayList, appFilePath, amplifucationDBHelper,
	// contextString);
	// saveMuData(arrayList, appFilePath, amplifucationDBHelper, contextString);
	// // }
	// // });
	// // thread.start();
	// }

	/**
	 * 保存溶解度光强
	 * 
	 * @param appFilePath
	 * @param isDeltEnd
	 * @param arrayListDelt
	 */
	public synchronized void saveDeletLightDate(
			final ArrayList<MethodBean> activityMethodBeans,
			final DeletDBHelper dbHelper, final String appFilePath,
			boolean isDeltEnd, final int channelSize,
			final StringBuffer contextString) {
		// Thread thread = new Thread(new Runnable() {
		// @Override
		// public void run() {
		saveMeltTempData(activityMethodBeans, dbHelper, appFilePath,
				channelSize, contextString);
		saveMeltNormalizedData(appFilePath, dbHelper, channelSize,
				contextString);
		saveMeltDerivativeData(activityMethodBeans, appFilePath, dbHelper,
				channelSize, contextString);

		// });
		// thread.start();
		// }
	}

	/**
	 * 
	 * 保存rawdata
	 * 
	 * @param arrayList
	 * @param appFilePath
	 */
	public synchronized void saveRawdata(
			AmplifucationDBHelper amplifucationDBHelper, String appFilePath) {
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\r\n");
		sBuffer.append("\r\n" + "Raw Data" + "\r\n");

		for (int channel = 1; channel <= 4; channel++) {
			sBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				sBuffer.append("\r\n" + "line" + (i + 1));
				if (amplifucationDBHelper.queryWhereChannel(channel).size() == 0) {

				} else {
					for (Float floatBean : amplifucationDBHelper.queryLine(i,
							channel)) {
						sBuffer.append("," + floatBean);
					}
				}

			}
			sBuffer.append("\r\n");

		}

		// 写文件 将数据写进文件

		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";
		String path = appFilePath + "/" + folderName;
		{
			// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据

			File file = new File(path + "/" + fileName);
			BufferedReader reader = null;
			try {
				System.out.println("以行为单位读取文件内容，一次读一整行:");
				reader = new BufferedReader(new FileReader(file));
				reader.close();

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
						// LogUtil.e("!!", contextString + "");

					} catch (IOException e1) {
					}
				}
			}

			fileManagerUtil.createFIle(folderName, fileName);
			fileManagerUtil.writeFile(folderName, fileName, "" + sBuffer, true);
			sBuffer = null;
		}
	}

	/**
	 * 
	 * 保存am
	 * 
	 * @param arrayList
	 * @param appFilePath
	 * @param amplifucationDBHelper
	 * @param contextString
	 */
	public synchronized void saveAmpdata(
			AmplifucationDBHelper amplifucationDBHelper, String appFilePath,
			StringBuffer contextString) {
		StringBuffer amBuffer = new StringBuffer();
		amplifucationDBHelper = new AmplifucationDBHelper(
				BaseApplication.getContext());
		amBuffer.append("\r\n" + "Amplification Data" + "\r\n");

		for (int channel = 1; channel <= 4; channel++) {
			amBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				amBuffer.append("\r\n" + "line" + (i + 1));
				if (amplifucationDBHelper.queryWhereChannel(channel).size() == 0) {

				} else {
					for (String floatBean : amplicMethod(
							amplifucationDBHelper.queryLine(i, channel),
							contextString, amplifucationDBHelper)) {
						amBuffer.append("," + floatBean);
					}
				}

			}
			amBuffer.append("\r\n");

		}

		// 写文件 将数据写进文件
		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";
		String path = appFilePath + "/" + folderName;
		// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
		File amfile = new File(path + "/" + fileName);
		BufferedReader amreader = null;
		StringBuffer amwriteText = new StringBuffer();
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行:");
			amreader = new BufferedReader(new FileReader(amfile));
			amreader.close();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (amreader != null) {
				try {
					amreader.close();
					// LogUtil.e("!!", contextString + "");

				} catch (IOException e1) {
				}
			}
		}

		fileManagerUtil.createFIle(folderName, fileName);
		fileManagerUtil.writeFile(folderName, fileName, "" + amwriteText
				+ amBuffer, true);
		amwriteText = null;
		amBuffer = null;
	}

	/**
	 * 保存mu
	 * 
	 * @param arrayList
	 * @param appFilePath
	 * @param amplifucationDBHelper
	 * @param contextString
	 */
	public synchronized void saveMuData(String appFilePath,
			AmplifucationDBHelper amplifucationDBHelper,
			StringBuffer contextString) {

		// Multicomponent Data
		StringBuffer muBuffer = new StringBuffer();
		muBuffer.append("\r\n" + "Multicomponent Data" + "\r\n");

		for (int channel = 1; channel <= 4; channel++) {
			muBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				muBuffer.append("\r\n" + "line" + (i + 1));
				if (amplifucationDBHelper.queryWhereChannel(channel).size() == 0) {

				} else {
					// ArrayList<String> arrayListRawIn = new
					// ArrayList<String>();
					// arrayListRawIn = amplifucationDBHelper.queryLine(
					// amplifucationDBHelper.sqlDB(), i, channel);
					for (String floatBean : muMethod(
							amplifucationDBHelper.queryLine(i, channel),
							contextString)) {
						// arrayList.get(channel).get(i)
						muBuffer.append("," + floatBean);
					}
				}

			}
			muBuffer.append("\r\n");

		}
		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";

		// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
		String path = appFilePath + "/" + folderName;
		File mufile = new File(path + "/" + fileName);
		BufferedReader mureader = null;
		StringBuffer muwriteText = new StringBuffer();
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行:");
			mureader = new BufferedReader(new FileReader(mufile));

			mureader.close();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (mureader != null) {
				try {
					mureader.close();
					// LogUtil.e("!!", contextString + "");

				} catch (IOException e1) {
				}
			}
		}

		fileManagerUtil.createFIle(folderName, fileName);
		fileManagerUtil.writeFile(folderName, fileName, "" + muwriteText
				+ muBuffer, true);
		muBuffer = null;
		muwriteText = null;
	}

	// public synchronized void saveMuData(
	// HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList,
	// String appFilePath, AmplifucationDBHelper amplifucationDBHelper,
	// StringBuffer contextString) {
	//
	// // Multicomponent Data
	// StringBuffer muBuffer = new StringBuffer();
	// muBuffer.append("\r\n" + "Multicomponent Data" + "\r\n");
	//
	// for (int channel = 1; channel <= 4; channel++) {
	// muBuffer.append("\r\n" + "Channel" + channel);
	// for (int i = 0; i < 32; i++) {
	// muBuffer.append("\r\n" + "line" + (i + 1));
	// if (arrayList.get(channel) == null) {
	//
	// } else {
	// // ArrayList<String> arrayListRawIn = new
	// // ArrayList<String>();
	// // arrayListRawIn = amplifucationDBHelper.queryLine(
	// // amplifucationDBHelper.sqlDB(), i, channel);
	// for (String floatBean : muMethod(arrayList.get(channel)
	// .get(i), contextString)) {
	// // arrayList.get(channel).get(i)
	// muBuffer.append("," + floatBean);
	// }
	// }
	//
	// }
	// muBuffer.append("\r\n");
	//
	// }
	// FileManagerUtil fileManagerUtil = new FileManagerUtil();
	// // 创建文件
	// String folderName = SharedPreferencesUtils.get(
	// BaseApplication.getContext(),
	// BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
	// String fileName = SharedPreferencesUtils.get(
	// BaseApplication.getContext(),
	// BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";
	//
	// // 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
	// String path = appFilePath + "/" + folderName;
	// File mufile = new File(path + "/" + fileName);
	// BufferedReader mureader = null;
	// StringBuffer muwriteText = new StringBuffer();
	// try {
	// System.out.println("以行为单位读取文件内容，一次读一整行:");
	// mureader = new BufferedReader(new FileReader(mufile));
	//
	// mureader.close();
	//
	// } catch (IOException e) {
	// e.printStackTrace();
	// } finally {
	// if (mureader != null) {
	// try {
	// mureader.close();
	// // LogUtil.e("!!", contextString + "");
	//
	// } catch (IOException e1) {
	// }
	// }
	// }
	//
	// fileManagerUtil.createFIle(folderName, fileName);
	// fileManagerUtil.writeFile(folderName, fileName, "" + muwriteText
	// + muBuffer, true);
	// muBuffer = null;
	// muwriteText = null;
	// }

	/**
	 * 
	 * mujar包
	 * 
	 * @param arrayListRawIn
	 * @param contextString
	 * @return
	 */
	private ArrayList<String> muMethod(ArrayList<Float> arrayListRawIn,
			StringBuffer contextString) {
		ArrayList<String> arrayList = new ArrayList<String>();
		for (int i = 0; i < arrayListRawIn.size(); i++) {
			arrayList.add("" + arrayListRawIn.get(i));
		}
		AutoBaseline autoBaseline = new AutoBaseline();
		if (whichChannel(contextString) != null) {
			return autoBaseline.arrayListMultiOut(arrayList, arrayList, 1);
		} else {
			return autoBaseline.arrayListMultiOut(arrayList, arrayList, 0);
		}

	}

	/**
	 * @return arrayListCorrectionIn待定
	 */
	private ArrayList<String> arrayListCorrectionIn() {
		return null;

	}

	/**
	 * 
	 * 溶解度的温度
	 * 
	 * @param arrayListDelt
	 * @param appFilePath
	 */

	public synchronized void saveMeltTempData(
			ArrayList<MethodBean> activityMethodBeans, DeletDBHelper dbHelper,
			String appFilePath, int channelSize, StringBuffer contextString) {

		whichTarget(contextString);
		float stratDeletTemp = -1;
		float deletT = 0;
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			if (!TextUtils.isEmpty(activityMethodBeans.get(i).getDeltaT())) {
				stratDeletTemp = Float.parseFloat(activityMethodBeans
						.get(i - 1).getTemperature().trim());
				deletT = Float.parseFloat(activityMethodBeans.get(i)
						.getDeltaT().trim());
			}

		}
		ArrayList<Float> stratDeletTemplist = new ArrayList<Float>();
		for (int i = 0; i < channelSize; i++) {
			if (stratDeletTemp == -1) {

			} else {
				float s = (stratDeletTemp + i * deletT);
				DecimalFormat decimalFormat = new DecimalFormat("#.0");
				stratDeletTemplist
						.add(Float.parseFloat(decimalFormat.format(s)));
			}

		}

		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\r\n" + "Melt Region Temperature Data" + "\r\n");
		SharedPreferences preferences = BaseApplication.getContext()
				.getSharedPreferences("MeltRegionTemperatureData",
						Context.MODE_PRIVATE);
		preferences.getString("filePath", "");
		preferences.getString("Reagent", "");
		preferences.getString("PassReference", "");
		sBuffer.append("Chemistry," + preferences.getString("Reagent", "")
				+ "\r\n");
		sBuffer.append("Experiment File Name,"
				+ preferences.getString("filePath", "") + "\r\n");
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		sBuffer.append("Experiment Run End Time,"
				+ dateFormat.format(System.currentTimeMillis()) + "\r\n");
		sBuffer.append("Instrument Type," + "Gene-32" + "\r\n");
		sBuffer.append("Passive Reference,"
				+ preferences.getString("PassReference", "") + "\r\n");
		int index = 0;
		for (int channel = 1; channel <= 4; channel++) {
			sBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				if (i == 0) {
					sBuffer.append("\r\n" + "Well" + "," + "Well Location"
							+ "," + "Target" + "," + "Report");

					for (int j = 0; j < channelSize; j++) {
						index++;
						sBuffer.append("," + "Reading " + index);
					}
					index = 0;
				}
				sBuffer.append("\r\n" + "" + (i + 1));
				if (dbHelper.queryWhereChannel(channel).size() == 0) {

				} else {
					if (i < 8) {
						sBuffer.append("," + "A" + (i + 1));

					}
					if (i >= 8 && i < 16) {
						sBuffer.append("," + "B" + (i - 7));

					}
					if (i >= 16 && i < 24) {
						sBuffer.append("," + "C" + (i - 15));

					}
					if (i >= 24) {
						sBuffer.append("," + "D" + (i - 23));

					}
					sBuffer.append("," + targetAndDyesString(i));
					// }

					// if (dbHelper.queryWhereChannel(channel).size() == 0) {
					//
					// } else {
					// if (stratDeletTemplist.size() != 0) {

					for (Float floatBean : stratDeletTemplist) {

						if (TextUtils.isEmpty(floatBean + "")) {

						} else {

							sBuffer.append("," + floatBean);
						}
					}
					// } else {
					// sBuffer.append(",");
					// }

				}

			}
			sBuffer.append("\r\n");

		}

		// 写文件 将数据写进文件

		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";

		// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
		String path = appFilePath + "/" + folderName;
		File file = new File(path + "/" + fileName);
		BufferedReader reader = null;
		try

		{
			System.out.println("以行为单位读取文件内容，一次读一整行:");
			reader = new BufferedReader(new FileReader(file));
			reader.close();

		} catch (

		IOException e)

		{
			e.printStackTrace();
		} finally

		{
			if (reader != null) {
				try {
					reader.close();
					// LogUtil.e("!!", contextString + "");

				} catch (IOException e1) {
				}
			}
		}

		fileManagerUtil.createFIle(folderName, fileName);
		fileManagerUtil.writeFile(folderName, fileName, "" + sBuffer, true);
		sBuffer = null;

	}

	public synchronized void saveMeltNormalizedData(String appFilePath,
			DeletDBHelper dbHelper, int channelSize, StringBuffer contextString) {
		whichTarget(contextString);
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\r\n" + "Melt Region Normalized Data" + "\r\n");
		SharedPreferences preferences = BaseApplication.getContext()
				.getSharedPreferences("MeltRegionTemperatureData",
						Context.MODE_PRIVATE);
		preferences.getString("filePath", "");
		preferences.getString("Reagent", "");
		preferences.getString("PassReference", "");
		sBuffer.append("Chemistry," + preferences.getString("Reagent", "")
				+ "\r\n");
		sBuffer.append("Experiment File Name,"
				+ preferences.getString("filePath", "") + "\r\n");
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		sBuffer.append("Experiment Run End Time,"
				+ dateFormat.format(System.currentTimeMillis()) + "\r\n");
		sBuffer.append("Instrument Type," + "Gene-32" + "\r\n");
		sBuffer.append("Passive Reference,"
				+ preferences.getString("PassReference", "") + "\r\n");
		int index = 0;
		for (int channel = 1; channel <= 4; channel++) {
			sBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				if (i == 0) {
					sBuffer.append("\r\n" + "Well" + "," + "Well Location"
							+ "," + "Target" + "," + "Report");

					for (int j = 0; j < channelSize; j++) {
						index++;
						sBuffer.append("," + "Reading " + index);
					}
					index = 0;
				}
				sBuffer.append("\r\n" + "" + (i + 1));
				if (dbHelper.queryWhereChannel(channel).size() == 0) {

				} else {
					if (i < 8) {
						sBuffer.append("," + "A" + (i + 1));

					}
					if (i >= 8 && i < 16) {
						sBuffer.append("," + "B" + (i - 7));

					}
					if (i >= 16 && i < 24) {
						sBuffer.append("," + "C" + (i - 15));

					}
					if (i >= 24) {
						sBuffer.append("," + "D" + (i - 23));

					}
					sBuffer.append("," + targetAndDyesString(i));
					for (String floatBean : dbHelper.queryLine(i, channel)) {

						if (TextUtils.isEmpty(floatBean + "")) {

						} else {

							sBuffer.append("," + floatBean);
						}
					}
				}

			}
			sBuffer.append("\r\n");

		}

		// 写文件 将数据写进文件

		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";

		// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
		String path = appFilePath + "/" + folderName;
		File file = new File(path + "/" + fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行:");
			reader = new BufferedReader(new FileReader(file));
			reader.close();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
					// LogUtil.e("!!", contextString + "");

				} catch (IOException e1) {
				}
			}
		}

		fileManagerUtil.createFIle(folderName, fileName);
		fileManagerUtil.writeFile(folderName, fileName, "" + sBuffer, true);
		sBuffer = null;
	}

	public synchronized void saveMeltDerivativeData(
			ArrayList<MethodBean> activityMethodBeans, String appFilePath,
			DeletDBHelper dbHelper, int channelSize, StringBuffer contextString) {
		whichTarget(contextString);
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\r\n" + "Melt Region Derivative Data" + "\r\n");
		SharedPreferences preferences = BaseApplication.getContext()
				.getSharedPreferences("MeltRegionTemperatureData",
						Context.MODE_PRIVATE);
		preferences.getString("filePath", "");
		preferences.getString("Reagent", "");
		preferences.getString("PassReference", "");
		sBuffer.append("Chemistry," + preferences.getString("Reagent", "")
				+ "\r\n");
		sBuffer.append("Experiment File Name,"
				+ preferences.getString("filePath", "") + "\r\n");
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		sBuffer.append("Experiment Run End Time,"
				+ dateFormat.format(System.currentTimeMillis()) + "\r\n");
		sBuffer.append("Instrument Type," + "Gene-32" + "\r\n");
		sBuffer.append("Passive Reference,"
				+ preferences.getString("PassReference", "") + "\r\n");
		int index = 0;
		for (int channel = 1; channel <= 4; channel++) {
			sBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				if (i == 0) {
					sBuffer.append("\r\n" + "Well" + "," + "Well Location"
							+ "," + "Target" + "," + "Report");

					for (int j = 0; j < channelSize; j++) {
						index++;
						sBuffer.append("," + "Reading " + index);
					}
					index = 0;
				}
				sBuffer.append("\r\n" + "" + (i + 1));
				if (dbHelper.queryWhereChannel(channel).size() == 0) {

				} else {
					if (i < 8) {
						sBuffer.append("," + "A" + (i + 1));
					}
					if (i >= 8 && i < 16) {
						sBuffer.append("," + "B" + (i - 7));
					}
					if (i >= 16 && i < 24) {
						sBuffer.append("," + "C" + (i - 15));

					}
					if (i >= 24) {
						sBuffer.append("," + "D" + (i - 23));

					}
					sBuffer.append("," + targetAndDyesString(i));
					AutoBaseline autoBaseline = new AutoBaseline();
					ArrayList<String> dbList = new ArrayList<String>();
					dbList = dbHelper.queryLine(i, channel);
					for (double floatBean : autoBaseline.getDeriValue(
							DerivativeTemp(activityMethodBeans, dbList.size()),
							DerivativepY(dbList), dbList.size())) {

						if (TextUtils.isEmpty(floatBean + "")) {

						} else {

							sBuffer.append("," + floatBean);
						}
					}
				}

			}
			sBuffer.append("\r\n");

		}

		// 写文件 将数据写进文件

		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";

		// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
		String path = appFilePath + "/" + folderName;
		File file = new File(path + "/" + fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行:");
			reader = new BufferedReader(new FileReader(file));
			reader.close();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
					// LogUtil.e("!!", contextString + "");

				} catch (IOException e1) {
				}
			}
		}

		fileManagerUtil.createFIle(folderName, fileName);
		fileManagerUtil.writeFile(folderName, fileName, "" + sBuffer, true);
		sBuffer = null;
	}

	private double[] DerivativeTemp(ArrayList<MethodBean> activityMethodBeans,
			int channelSize) {
		float stratDeletTemp = -1;
		float deletT = 0;
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			if (!TextUtils.isEmpty(activityMethodBeans.get(i).getDeltaT())) {
				stratDeletTemp = Float.parseFloat(activityMethodBeans
						.get(i - 1).getTemperature().trim());
				deletT = Float.parseFloat(activityMethodBeans.get(i)
						.getDeltaT().trim());
			}

		}
		ArrayList<Float> stratDeletTemplist = new ArrayList<Float>();
		for (int i = 0; i < channelSize; i++) {
			if (stratDeletTemp ==-1) {

			} else {
				float s = (stratDeletTemp + i * deletT);
				DecimalFormat decimalFormat = new DecimalFormat("#.0");
				stratDeletTemplist
						.add(Float.parseFloat(decimalFormat.format(s)));
			}
		}
		double[] deri = new double[stratDeletTemplist.size()];
		for (int j = 0; j < deri.length; j++) {
			deri[j] = stratDeletTemplist.get(j);
		}
		return deri;

	}

	private double[] DerivativepY(ArrayList<String> arrayList) {
		double[] deri = new double[arrayList.size()];
		for (int j = 0; j < deri.length; j++) {
			deri[j] = Double.parseDouble(arrayList.get(j));
		}
		return deri;

	}

	/**
	 * 拍照光强
	 * 
	 * @param pack
	 * @param rightPhotoCount
	 * @param arrayList
	 * @param channelList
	 * @param channelIndex
	 */
	public void photoLight(final DetectLightIntensitTempRespPacket pack,
			AmplifucationDBHelper amplifucationDBHelper,
			final int rightPhotoCount,
			final HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList,
			final ArrayList<String> channelList, final int channelIndex) {
		// Thread photoLightthread = new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		ArrayList<Float> pointArray = new ArrayList<Float>();
		ArrayList<ArrayList<Float>> lineArray = new ArrayList<ArrayList<Float>>();
		int index = 0;
		// String content =
		// "4751,288142,3757,297643,3475,295346,3413,310624,4084,307598,4078,286539,3360,310190,3498,287512,3926,316789,3849,328266,3879,322429,3939,326913,3570,331819,3752,318723,3655,310438,3201,300300,";
		String content = pack.returnData();

		// 通道号 channelIndex+1
		for (int i = 0; i < 32; i++) {
			// point
			// content.substring(index, content.indexOf(",",index));
			pointArray = new ArrayList<Float>();
			// amplifucationDBHelper.add(
			// (Integer.parseInt(channelList.get(channelIndex))) + "",
			// content.substring(index, content.indexOf(",", index)), (i)
			// + "", rightPhotoCount + "");
			// 如果是第一周期，不是第一周期
			if (rightPhotoCount == 1) {
				// 线
				pointArray.add(Float.parseFloat(content.substring(index,
						content.indexOf(",", index))));
				index = content.indexOf(",", index) + 1;
				lineArray.add(i, pointArray);
			} else {
				arrayList
						.get(Integer.parseInt(channelList.get(channelIndex)))
						.get(i)
						.add(Float.parseFloat(content.substring(index,
								content.indexOf(",", index))));
				pointArray.add(Float.parseFloat(content.substring(index,
						content.indexOf(",", index))));
				lineArray.add(i, pointArray);
				index = content.indexOf(",", index) + 1;
				// }

			}

			//
			// // 线
			//
			// lineArray.add(i, pointArray);

		}
		if (rightPhotoCount == 1) {
			// 通道
			// if (channelIndex < channelList.size()) {
			arrayList.put(Integer.parseInt(channelList.get(channelIndex)),
					lineArray);
			// }

		}
		// }
		// });
		// photoLightthread.start();
	}

	/**
	 * 
	 * 获取当前所有时间
	 * 
	 * @param activityMethodBeans
	 *            实体类
	 * @param TempUpCoefficient
	 *            升温系数
	 * @param TempDownCoefficient
	 *            降温
	 * @param HotTempUpCoefficient
	 *            热盖升温
	 * @param tragethotTemp
	 *            热盖目标温度
	 * @param hotTemp
	 *            热盖当前温度
	 * @param nowTemp
	 *            模块1 当前温度
	 * @param channelnum
	 * 
	 * @return
	 */
	double changePhotoCountTime(ArrayList<MethodBean> activityMethodBeans,
			double TempUpCoefficient, double TempDownCoefficient,
			double HotTempUpCoefficient, double tragethotTemp, double hotTemp,
			double nowTemp, int channelnum, int PhotoBackCount) {
		int step = 1;
		double time = 0;
		double deletT = 0;
		double stratDeletTemp = 0;
		double targetDeletTemp = 0;
		int channelSize = 0;
		int RightStep = 0;
		double photoTime = 5000;
		double firstTemp = Double.parseDouble(activityMethodBeans.get(0)
				.getTemperature().replace("℃", ""));
		TimeCountUtils ssCount = new TimeCountUtils();
		// 结束步骤
		int endstep = activityMethodBeans.size();
		// 每个点循环次数的标记位
		HashMap<Integer, Integer> stepNum = new HashMap<Integer, Integer>();
		for (int i = 1; i <= 20; i++) {
			// stepNum.put(i, 0);
			stepNum.put(i, 1);
		}
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			if (!TextUtils.isEmpty(activityMethodBeans.get(i).getDeltaT())) {
				stratDeletTemp = Double.parseDouble(activityMethodBeans
						.get(i - 1).getTemperature().trim());
				targetDeletTemp = Double.parseDouble(activityMethodBeans.get(i)
						.getTemperature().trim());
				deletT = Double.parseDouble(activityMethodBeans.get(i)
						.getDeltaT().trim());
				channelSize = (int) ((Math
						.abs(((targetDeletTemp - stratDeletTemp)))) / deletT) + 1;

			}

		}
		time += channelSize * photoTime * 2 * channelnum;
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			if ((activityMethodBeans.get(i).getRightSelect())) {
				if (!TextUtils.isEmpty(activityMethodBeans.get(i)
						.getRepititions().trim())) {
					RightStep = i + 1;
					time += (PhotoBackCount) * photoTime * channelnum;
				}

			}
		}
		if (nowTemp > firstTemp) {
			time += (nowTemp - firstTemp) * TempDownCoefficient;
		} else if (nowTemp < firstTemp) {

			time += (firstTemp - nowTemp) * TempUpCoefficient;
		}

		if ((tragethotTemp - hotTemp) > 5) {
			time += ((tragethotTemp - 5) - hotTemp) * HotTempUpCoefficient;
		}
		while (true) {

			// time=nowTemp
			if (TextUtils.isEmpty(activityMethodBeans.get(step - 1).getGoTo())) {
				// 没有goto

				if (endstep == step) {
					time = time
							+ ssCount.TimeCalculation(activityMethodBeans.get(
									step - 1).getTime());
					// Log.i("!!!!!!time", time + "");
					break;
				} else {
					// Log.i("!!!!!!time", time + "");
					time = time
							+ ssCount.TimeCalculation(activityMethodBeans.get(
									step - 1).getTime());
					// Log.e("hu1", "nogto温差时间方法" + step);

					// 计算上升时间
					double a = Double.parseDouble(activityMethodBeans
							.get(step - 1).getTemperature().replace("℃", ""));
					double b = Double.parseDouble(activityMethodBeans.get(step)
							.getTemperature().replace("℃", ""));
					if (a > b) {
						time = time + (a - b) * TempDownCoefficient;
					} else {
						time = time + (b - a) * TempUpCoefficient;
					}

				}
				step++;

			} else {
				// 有goto
				// 先判断是不是最后一步。是最后一步return；不是继续往下一步跳
				if (endstep == step) {
					// 判断循环标记位是否和循环数一样。如果一样置零然后结束。不一样进入goto循环
					int reception = Integer.parseInt(activityMethodBeans
							.get(step - 1).getRepititions().trim());
					if (step == RightStep) {
						reception = PhotoBackCount;
					}
					if (stepNum.get(step) == reception) {
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						// Log.i("!!!!!!time", time + "");
						// Log.e("hu2", "end ==repition温差时间方法" + step);
						break;
					} else {
						int oldStep = step;
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						stepNum.put(step, stepNum.get(step) + 1);
						Log.e("hu2", "end norepition温差时间方法" + step);
						// Log.i("!!!!!!time", time + "");
						step = Integer.parseInt(activityMethodBeans
								.get(step - 1).getGoTo().trim());

						// 计算上升时间
						double a = Double.parseDouble(activityMethodBeans
								.get(step - 1).getTemperature()
								.replace("℃", ""));
						double b = Double.parseDouble(activityMethodBeans
								.get(oldStep - 1).getTemperature()
								.replace("℃", ""));
						if (a > b) {
							time = time + (a - b) * TempUpCoefficient;
						} else {
							time = time + (b - a) * TempDownCoefficient;
						}

					}
				} else {
					int reception = Integer.parseInt(activityMethodBeans
							.get(step - 1).getRepititions().trim());
					if (step == RightStep) {
						reception = PhotoBackCount;
					}
					if (stepNum.get(step) == reception) {
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						stepNum.put(step, 1);
						// Log.e("hu3", "end ==repition温差时间方法温差时间方法" + step);
						// Log.i("!!!!!!time", time + "");

						// 计算上升时间
						double a = Double.parseDouble(activityMethodBeans
								.get(step - 1).getTemperature()
								.replace("℃", ""));
						double b = Double.parseDouble(activityMethodBeans
								.get(step).getTemperature().replace("℃", ""));
						if (a > b) {
							time = time + (a - b) * TempDownCoefficient;
						} else {
							time = time + (b - a) * TempUpCoefficient;
						}
						step++;
					} else {
						int oldStep = step;
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						stepNum.put(step, stepNum.get(step) + 1);
						// Log.i("!!!!!!time", time + "");
						// Log.e("hu4", "end no=repition温差时间方法温差时间方法" + step);
						step = Integer.parseInt(activityMethodBeans
								.get(step - 1).getGoTo().trim());

						// 计算上升时间
						double a = Double.parseDouble(activityMethodBeans
								.get(step - 1).getTemperature()
								.replace("℃", ""));
						double b = Double.parseDouble(activityMethodBeans
								.get(oldStep - 1).getTemperature()
								.replace("℃", ""));
						if (a > b) {
							time = time + (a - b) * TempUpCoefficient;
						} else {
							time = time + (b - a) * TempDownCoefficient;
						}

					}
				}

			}
			SystemClock.sleep(1);
		}
		return time;
	}

	/**
	 * 
	 * 获取当前所有时间
	 * 
	 * @param activityMethodBeans
	 *            实体类
	 * @param TempUpCoefficient
	 *            升温系数
	 * @param TempDownCoefficient
	 *            降温
	 * @param HotTempUpCoefficient
	 *            热盖升温
	 * @param tragethotTemp
	 *            热盖目标温度
	 * @param hotTemp
	 *            热盖当前温度
	 * @param nowTemp
	 *            模块1 当前温度
	 * @param channelnum
	 * 
	 * @return
	 */
	public double getTime(ArrayList<MethodBean> activityMethodBeans,
			double TempUpCoefficient, double TempDownCoefficient,
			double HotTempUpCoefficient, double tragethotTemp, double hotTemp,
			double nowTemp, int channelnum) {
		int step = 1;
		double time = 0;
		double deletT = 0;
		double stratDeletTemp = 0;
		double targetDeletTemp = 0;
		int channelSize = 0;
		double photoTime = 5000;
		double firstTemp = Double.parseDouble(activityMethodBeans.get(0)
				.getTemperature().replace("℃", ""));
		TimeCountUtils ssCount = new TimeCountUtils();
		// 结束步骤
		int endstep = activityMethodBeans.size();
		// 每个点循环次数的标记位
		HashMap<Integer, Integer> stepNum = new HashMap<Integer, Integer>();
		for (int i = 1; i <= 20; i++) {
			// stepNum.put(i, 0);
			stepNum.put(i, 1);
		}
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			if (!TextUtils.isEmpty(activityMethodBeans.get(i).getDeltaT())) {
				stratDeletTemp = Double.parseDouble(activityMethodBeans
						.get(i - 1).getTemperature().trim());
				targetDeletTemp = Double.parseDouble(activityMethodBeans.get(i)
						.getTemperature().trim());
				deletT = Double.parseDouble(activityMethodBeans.get(i)
						.getDeltaT().trim());
				channelSize = (int) ((Math
						.abs(((targetDeletTemp - stratDeletTemp)))) / deletT) + 1;

			}

		}
		time += channelSize * photoTime * (2 + (channelnum - 1));
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			if ((activityMethodBeans.get(i).getRightSelect())) {
				if (!TextUtils.isEmpty(activityMethodBeans.get(i)
						.getRepititions().trim())) {
					time += (Integer.parseInt(activityMethodBeans.get(i)
							.getRepititions().trim()))
							* photoTime * channelnum;
				} else {
					time += photoTime * channelnum;
				}

			}
		}
		if (nowTemp > firstTemp) {
			time += (nowTemp - firstTemp) * TempDownCoefficient;
		} else if (nowTemp < firstTemp) {

			time += (firstTemp - nowTemp) * TempUpCoefficient;
		}

		if ((tragethotTemp - hotTemp) > 5) {
			time += ((tragethotTemp - 5) - hotTemp) * HotTempUpCoefficient;
		}
		while (true) {
			// time=nowTemp
			if (TextUtils.isEmpty(activityMethodBeans.get(step - 1).getGoTo())) {
				// 没有goto

				if (endstep == step) {
					time = time
							+ ssCount.TimeCalculation(activityMethodBeans.get(
									step - 1).getTime());
					// Log.i("!!!!!!time", time + "");
					break;
				} else {
					// Log.i("!!!!!!time", time + "");
					time = time
							+ ssCount.TimeCalculation(activityMethodBeans.get(
									step - 1).getTime());
					// Log.e("hu1", "nogto温差时间方法" + step);

					// 计算上升时间
					double a = Double.parseDouble(activityMethodBeans
							.get(step - 1).getTemperature().replace("℃", ""));
					double b = Double.parseDouble(activityMethodBeans.get(step)
							.getTemperature().replace("℃", ""));
					if (a > b) {
						time = time + (a - b) * TempDownCoefficient;
					} else {
						time = time + (b - a) * TempUpCoefficient;
					}

				}
				step++;

			} else {
				// 有goto
				// 先判断是不是最后一步。是最后一步return；不是继续往下一步跳
				if (endstep == step) {
					// 判断循环标记位是否和循环数一样。如果一样置零然后结束。不一样进入goto循环
					if (stepNum.get(step) == Integer
							.parseInt(activityMethodBeans.get(step - 1)
									.getRepititions().trim())) {
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						// Log.i("!!!!!!time", time + "");
						// Log.e("hu2", "end ==repition温差时间方法" + step);
						break;
					} else {
						int oldStep = step;
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						stepNum.put(step, stepNum.get(step) + 1);
						// Log.i("hu!!!!!!", step + "");
						// Log.e("hu2", "end norepition温差时间方法" + step);
						// Log.i("!!!!!!time", time + "");
						step = Integer.parseInt(activityMethodBeans
								.get(step - 1).getGoTo().trim());

						// 计算上升时间
						double a = Double.parseDouble(activityMethodBeans
								.get(step - 1).getTemperature()
								.replace("℃", ""));
						double b = Double.parseDouble(activityMethodBeans
								.get(oldStep - 1).getTemperature()
								.replace("℃", ""));
						if (a > b) {
							time = time + (a - b) * TempUpCoefficient;
						} else {
							time = time + (b - a) * TempDownCoefficient;
						}

					}
				} else {
					if (stepNum.get(step) == Integer
							.parseInt(activityMethodBeans.get(step - 1)
									.getRepititions().trim())) {
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						stepNum.put(step, 1);
						// Log.i("hu!!!!!!", step + "");
						// Log.i("!!!!!!time", time + "");

						// 计算上升时间
						double a = Double.parseDouble(activityMethodBeans
								.get(step - 1).getTemperature()
								.replace("℃", ""));
						double b = Double.parseDouble(activityMethodBeans
								.get(step).getTemperature().replace("℃", ""));
						if (a > b) {
							time = time + (a - b) * TempDownCoefficient;
						} else {
							time = time + (b - a) * TempUpCoefficient;
						}
						step++;
					} else {
						int oldStep = step;
						time = time
								+ ssCount.TimeCalculation(activityMethodBeans
										.get(step - 1).getTime());
						stepNum.put(step, stepNum.get(step) + 1);
						// Log.i("!!!!!!time", time + "");
						// Log.e("hu4", "end no=repition温差时间方法温差时间方法" + step);
						step = Integer.parseInt(activityMethodBeans
								.get(step - 1).getGoTo().trim());

						// 计算上升时间
						double a = Double.parseDouble(activityMethodBeans
								.get(step - 1).getTemperature()
								.replace("℃", ""));
						double b = Double.parseDouble(activityMethodBeans
								.get(oldStep - 1).getTemperature()
								.replace("℃", ""));
						if (a > b) {
							time = time + (a - b) * TempUpCoefficient;
						} else {
							time = time + (b - a) * TempDownCoefficient;
						}

					}
				}

			}
			SystemClock.sleep(1);
		}
		return time;
	}

	/**
	 * 保存温度
	 * 
	 * @param appFilePath
	 * @param mode1arrayList
	 * @param mode2arrayList
	 * @param mode3arrayList
	 */
	public synchronized void saveTempdate(final String appFilePath,
			final ArrayList<String> mode1arrayList,
			final ArrayList<String> mode2arrayList,
			final ArrayList<String> mode3arrayList) {
		// Thread thread = new Thread(new Runnable() {
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\r\n");
		sBuffer.append("\r\n" + "Temp Data" + "\r\n");
		sBuffer.append("Mode1Temp\r\n");
		for (int i = 0; i < mode1arrayList.size(); i++) {
			if (i > 0 && i % 200 == 0) {
				sBuffer.append("\r\n");
			}
			sBuffer.append(mode1arrayList.get(i) + ",");
		}
		sBuffer.append("\r\n");
		sBuffer.append("Mode2Temp\r\n");
		for (int i = 0; i < mode2arrayList.size(); i++) {
			if (i > 0 && i % 200 == 0) {
				sBuffer.append("\r\n");
			}
			sBuffer.append(mode2arrayList.get(i) + ",");
		}
		sBuffer.append("\r\n");
		sBuffer.append("Mode3Temp\r\n");
		for (int i = 0; i < mode3arrayList.size(); i++) {
			if (i > 0 && i % 200 == 0) {
				sBuffer.append("\r\n");
			}
			sBuffer.append(mode3arrayList.get(i) + ",");
		}
		sBuffer.append("\r\n");
		// 写文件 将数据写进文件

		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";

		// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据
		// String path = appFilePath + "/" + folderName;
		// File file = new File(path + "/" + fileName);
		// BufferedReader reader = null;
		// StringBuffer writeText = new StringBuffer();
		// try {
		// System.out.println("以行为单位读取文件内容，一次读一整行:");
		// reader = new BufferedReader(new FileReader(file));
		// reader.close();
		//
		// } catch (IOException e) {
		// e.printStackTrace();
		// } finally {
		// if (reader != null) {
		// try {
		// reader.close();
		// // LogUtil.e("!!", contextString + "");
		//
		// } catch (IOException e1) {
		// }
		// }
		// }

		fileManagerUtil.createFIle(folderName, fileName);
		fileManagerUtil.writeFile(folderName, fileName, "" + sBuffer, true);
		// }
		// });
		// thread.start();
	}

	/**
	 * 更新循环次数
	 * 
	 */
	public synchronized void updateRepititions(
			final ArrayList<MethodBean> activityMethodBeans,
			final String repititions) {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				String folderName = SharedPreferencesUtils.get(
						BaseApplication.getContext(),
						BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "") + "";
				String fileName = SharedPreferencesUtils.get(
						BaseApplication.getContext(),
						BaseApplication.FILEMANGER_PREPAREFILENAME, "") + "";
				String appFilePath = Environment.getExternalStorageDirectory()
						+ "/" + "AllShengMedical";
				String path = appFilePath + "/" + folderName;

				File file = new File(path + "/" + fileName);
				BufferedReader reader = null;
				StringBuffer contextString = new StringBuffer();
				try {
					System.out.println("以行为单位读取文件内容，一次读一整行:");
					reader = new BufferedReader(new FileReader(file));
					String tempString = null;
					int line = 1;
					boolean writeflag = false;
					// 一次读入一行，直到读入null为文件结束
					while ((tempString = reader.readLine()) != null) {
						// 显示行号
						// System.out.println("line " + line + ": " +
						// tempString);
						// Log.e("--", tempString);
						// if (tempString.equals("dataSourceListBlock1")) {
						// break;
						// } else {
						//
						// }

						if (tempString.toString().contains("Methods")) {
							writeflag = true;
							// contextString.append("\r\n" + "\r\n" + "Methods"
							// +
							// "\r\n");
							contextString.append("Methods" + "\r\n");
							for (MethodBean bean : activityMethodBeans) {
								contextString.append("\r\n" + "steptType: "
										+ bean.getSteptType());
								contextString.append("\r\n" + "temperature: "
										+ bean.getTemperature());
								contextString.append("\r\n" + "time: "
										+ bean.getTime());
								contextString.append("\r\n" + "goTo: "
										+ bean.getGoTo());
								contextString.append("\r\n" + "Repititions: "
										+ bean.getRepititions());
								contextString.append("\r\n" + "deltaT: "
										+ bean.getDeltaT());
								contextString.append("\r\n" + "rightSelect: "
										+ bean.getRightSelect());

							}
							contextString.append("\r\n");
							contextString.append("\r\n");
						} else if (tempString.toString().contains("pointMap")) {
							writeflag = false;
						}

						if (writeflag) {

						} else {
							contextString.append(tempString);
							contextString.append("\r\n");
						}

						line++;
						SystemClock.sleep(1);
					}
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (reader != null) {
						try {
							reader.close();
							// LogUtil.e("!!", contextString + "");

						} catch (IOException e1) {
						}
					}
				}
				FileManagerUtil fileManagerUtil = new FileManagerUtil();
				fileManagerUtil.createFIle(folderName, fileName);
				fileManagerUtil.writeFile(folderName, fileName, contextString
						.toString().trim(), false);
			}

		});
		thread.start();
	}

	public void saveRawdata2(List<LayoutTableBean> activityLayoutTableBeans,
			HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList,
			String appFilePath, int channelsize, StringBuffer contextString) {
		int channelSize = 0;
		float stratDeletTemp = 0;
		float targetDeletTemp = 0;
		whichTarget(contextString);
		float deletT = 0;
		stratDeletTemp = Float.parseFloat(60 + "");
		targetDeletTemp = Float.parseFloat(95 + "");
		deletT = Float.parseFloat(0.3 + "");
		if ((int) ((Math.abs(((targetDeletTemp - stratDeletTemp)))) % deletT) == 0) {
			channelSize = (int) ((Math
					.abs(((targetDeletTemp - stratDeletTemp)))) / deletT) + 1;

		} else {
			channelSize = (int) ((Math
					.abs(((targetDeletTemp - stratDeletTemp)))) / deletT);

		}

		ArrayList<Float> stratDeletTemplist = new ArrayList<Float>();
		for (Float i = 0f; i < channelSize; i++) {
			float s = (stratDeletTemp + i * deletT);
			DecimalFormat decimalFormat = new DecimalFormat("#.0");
			decimalFormat.format(s);
			stratDeletTemplist.add(Float.parseFloat(decimalFormat.format(s)));
		}

		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\r\n");
		sBuffer.append("\r\n" + "XXXX" + "\r\n");
		int index = 0;
		for (int channel = 1; channel <= 4; channel++) {
			sBuffer.append("\r\n" + "Channel" + channel);
			for (int i = 0; i < 32; i++) {
				if (i == 0) {

					sBuffer.append("\r\n" + "Well" + "," + "Well Location"
							+ "," + "Target" + "," + "Report");

					for (int j = 0; j < channelSize; j++) {
						index++;
						sBuffer.append("," + "Reading " + index);
					}
					index = 0;
				}
				sBuffer.append("\r\n" + "" + (i + 1));
				if (arrayList.get(channel) == null) {

				} else {
					if (i < 8) {
						sBuffer.append("," + "A" + (i + 1));
						sBuffer.append("," + targetAndDyesString(i));

					}
					if (i >= 8 && i < 16) {
						sBuffer.append("," + "B" + (i - 7));
						if (indexArrayList.size() != 0) {
							sBuffer.append(","
									+ targetarrayList.get(indexArrayList.get(i)));
							sBuffer.append(","
									+ DyesarrayList.get(indexArrayList.get(i)));
						} else {
							sBuffer.append(",");
							sBuffer.append(",");
						}
					}
					if (i >= 16 && i < 24) {
						sBuffer.append("," + "C" + (i - 15));
						if (indexArrayList.size() != 0) {
							sBuffer.append(","
									+ targetarrayList.get(indexArrayList.get(i)));
							sBuffer.append(","
									+ DyesarrayList.get(indexArrayList.get(i)));
						} else {
							sBuffer.append(",");
							sBuffer.append(",");
						}
					}
					if (i >= 24) {
						sBuffer.append("," + "D" + (i - 23));
						if (indexArrayList.size() != 0) {
							sBuffer.append(","
									+ targetarrayList.get(indexArrayList.get(i)));
							sBuffer.append(","
									+ DyesarrayList.get(indexArrayList.get(i)));
						} else {
							sBuffer.append(",");
							sBuffer.append(",");
						}
					}

				}

				if (arrayList.get(channel) == null) {

				} else {
					for (Float floatBean : stratDeletTemplist) {
						sBuffer.append("," + floatBean);
					}
				}

			}
			sBuffer.append("\r\n");

		}

		// 写文件 将数据写进文件

		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		// 创建文件
		String folderName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "0") + "";
		String fileName = SharedPreferencesUtils.get(
				BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "0") + "";
		String path = appFilePath + "/" + folderName;
		{
			// 这个方法和之前的一样，先一行一行的全部取出来。然后当遇到本页面数据。我们不做添加然后在这时我们要加入接下来的文件的数据

			File file = new File(path + "/" + fileName);
			BufferedReader reader = null;
			StringBuffer writeText = new StringBuffer();
			try {
				System.out.println("以行为单位读取文件内容，一次读一整行:");
				reader = new BufferedReader(new FileReader(file));
				reader.close();

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
						// LogUtil.e("!!", contextString + "");

					} catch (IOException e1) {
					}
				}
			}

			fileManagerUtil.createFIle(folderName, fileName);
			fileManagerUtil.writeFile(folderName, fileName, "" + writeText
					+ sBuffer, true);
			sBuffer = null;
		}
	}

	public void whichTarget(StringBuffer contextString) {

		String target = null;
		String Dyes = null;
		String Color = null;
		int aisleindex = 0;
		// StringBuilder stringBuilder = new StringBuilder();

		while (!(contextString.indexOf("Aisle", aisleindex) <= 0)) {
			Color = contextString.substring(
					contextString.indexOf("Color:", aisleindex) + 6,
					contextString.indexOf(",Target", aisleindex)).trim();
			target = contextString.substring(
					contextString.indexOf(",Target:", aisleindex) + 8,
					contextString.indexOf(",Dyes", aisleindex)).trim();
			int nextIndex = contextString.indexOf(",Aisle", aisleindex) + 7;
			if (contextString.indexOf(",Aisle", nextIndex) < 0) {
				Dyes = contextString.substring(contextString.indexOf(",Dyes",
						aisleindex) + 6, contextString.indexOf(
						",,dataSourceListBlock1", aisleindex));
			} else {
				Dyes = contextString.substring(
						contextString.indexOf(",Dyes", aisleindex) + 6,
						contextString.indexOf(",Aisle", nextIndex));
			}

			targetarrayList.add(target);
			DyesarrayList.add(Dyes);
			ColorarrayList.add(Color);
			aisleindex = contextString.indexOf(",Dyes", aisleindex) + 5;
		}
		int index = 0;
		for (int i = 0; i < 16; i++) {
			String context = contextString.substring(
					contextString.indexOf("dataSourceListBlock1,,") + 22,
					contextString.indexOf(",,dataSourceListBlock2") + 22);
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			String item_image = context.substring(
					context.indexOf("item_image:", index) + 11,
					context.indexOf(",item_text:", index)).trim();
			String item_text = context.substring(
					context.indexOf("item_text:", index) + 10,
					context.indexOf(",item_selected:", index)).trim();
			Boolean item_selected = Boolean.getBoolean(context.substring(
					context.indexOf("item_selected:", index) + 14,
					context.indexOf(",item_null:", index)));

			boolean item_null = false;
			if ("null".equals(context.substring(
					context.indexOf("item_null:", index) + 10,
					context.indexOf(",item_aisle:", index)))) {
				item_null = true;
				hashMap.put("item_null", item_null);
			} else {
				item_null = false;
				hashMap.put("item_null", item_null);
			}
			int item_aisle = 0;
			if ("null".equals(context.substring(
					context.indexOf("item_aisle:", index) + 11,
					context.indexOf(",item_type:", index)).trim())) {

			} else {
				item_aisle = Integer.parseInt(context.substring(
						context.indexOf("item_aisle:", index) + 11,
						context.indexOf(",item_type:", index)).trim());
			}
			int nextIndex = context.indexOf("item_image:", index) + 11;
			String item_type = "";
			if (i == 15) {
				item_type = context.substring(
						context.indexOf("item_type:", index) + 10,
						context.indexOf(",,dataSourceListBlock2", index))
						.trim();

			} else {
				item_type = context.substring(
						context.indexOf("item_type:", index) + 10,
						context.indexOf(",item_image:", nextIndex)).trim();
			}

			hashMap.put("item_image", item_image);
			hashMap.put("item_text", item_text);
			hashMap.put("item_selected", item_selected);
			hashMap.put("item_aisle", item_aisle);
			hashMap.put("item_type", item_type);
			dataSourceListBlock1.add(hashMap);
			index = context.indexOf("item_type:", index) + 10;
		}
		index = 0;
		for (int i = 0; i < 16; i++) {
			String context = contextString.substring(
					contextString.indexOf("dataSourceListBlock2,,") + 22,
					contextString.indexOf(",,cameraSet") + 11);
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			String item_image = context.substring(
					context.indexOf("item_image:", index) + 11,
					context.indexOf(",item_text:", index)).trim();
			String item_text = context.substring(
					context.indexOf("item_text:", index) + 10,
					context.indexOf(",item_selected:", index)).trim();
			Boolean item_selected = Boolean.getBoolean(context.substring(
					context.indexOf("item_selected:", index) + 14,
					context.indexOf(",item_null:", index)));

			boolean item_null = false;
			if ("null".equals(context.substring(
					context.indexOf("item_null:", index) + 10,
					context.indexOf(",item_aisle:", index)))) {
				item_null = true;
				hashMap.put("item_null", item_null);
			} else {
				item_null = false;
				hashMap.put("item_null", item_null);
			}
			int item_aisle = 0;
			if ("null".equals(context.substring(
					context.indexOf("item_aisle:", index) + 11,
					context.indexOf(",item_type:", index)).trim())) {

			} else {
				item_aisle = Integer.parseInt(context.substring(
						context.indexOf("item_aisle:", index) + 11,
						context.indexOf(",item_type:", index)).trim());
			}

			int nextIndex = context.indexOf("item_image:", index) + 11;

			String item_type = "";
			if (context.indexOf("item_image:", nextIndex) < 0) {
				item_type = context.substring(
						context.indexOf("item_type:", index) + 10,
						context.indexOf(",,cameraSet", index)).trim();

			} else {
				if (i == 15) {

					// TODO 最后一位不出来颜色bug在这以后再改
					item_type = context.substring(
							context.indexOf("item_type:", index) + 10,
							context.indexOf(",,cameraSet", nextIndex)).trim();
				} else {
					item_type = context.substring(
							context.indexOf("item_type:", index) + 10,
							context.indexOf(",item_image:", nextIndex)).trim();
				}
			}
			hashMap.put("item_image", item_image);
			hashMap.put("item_text", item_text);
			hashMap.put("item_selected", item_selected);
			hashMap.put("item_aisle", item_aisle);
			hashMap.put("item_type", item_type);
			dataSourceListBlock2.add(hashMap);
			index = context.indexOf("item_type:", index) + 10;
		}

	}

	private String targetAndDyesString(int i) {
		String s = "";
		String s2 = "";
		if (i < 16) {
			for (int j = 0; j < ColorarrayList.size(); j++) {
				if (dataSourceListBlock1.get(i).get("item_image")
						.equals(ColorarrayList.get(j))) {
					s = targetarrayList.get(j);
					s2 = DyesarrayList.get(j);
				}
			}

		} else {
			for (int j = 0; j < ColorarrayList.size(); j++) {
				if (dataSourceListBlock2.get(i - 16).get("item_image")
						.equals(ColorarrayList.get(j))) {
					s = targetarrayList.get(j);
					s2 = DyesarrayList.get(j);
				}
			}

		}

		return s + "," + s2;

	}

	private ArrayList<String> amplicMethod(ArrayList<Float> arrayListRawIn,
			StringBuffer contextString,
			AmplifucationDBHelper amplifucationDBHelper) {
		ArrayList<String> arrayList = new ArrayList<String>();

		for (int i = 0; i < arrayListRawIn.size(); i++) {
			arrayList.add(arrayListRawIn.get(i) + "");
		}
		AutoBaseline autoBaseline = new AutoBaseline();
		if (contrastData(contextString, amplifucationDBHelper) != null) {
			return autoBaseline.arrayListRnOut(arrayList,
					contrastData(contextString, amplifucationDBHelper), 1, 0.5);
		} else {
			return autoBaseline.arrayListRnOut(arrayList, arrayList, 0, 0.5);
		}

	}

	public ArrayList<String> contrastData(StringBuffer contextString,
			AmplifucationDBHelper amplifucationDBHelper) {
		String passReferenceString = contextString.substring(
				contextString.indexOf("PassReference:") + 14,
				contextString.indexOf(",,")).trim();
		if (passReferenceString.equals("FAM")
				|| passReferenceString.equals("SYBR Green I")) {
			return amplifucationDBHelper.queryWhereChannel(1);

		} else if (passReferenceString.equals("HEX")
				|| passReferenceString.equals("JOE")
				|| passReferenceString.equals("CY3")
				|| passReferenceString.equals("TET")) {
			return amplifucationDBHelper.queryWhereChannel(2);
		} else if (passReferenceString.equals("ROX")
				|| passReferenceString.equals("TEXAS-RED")) {
			return amplifucationDBHelper.queryWhereChannel(3);
		} else if (passReferenceString.equals("CY5")) {
			return amplifucationDBHelper.queryWhereChannel(4);
		} else {
			return null;
		}

	}

	public String whichChannel(StringBuffer contextString) {
		String passReferenceString = contextString.substring(
				contextString.indexOf("PassReference:") + 14,
				contextString.indexOf(",,")).trim();
		if (passReferenceString.equals("FAM")
				|| passReferenceString.equals("SYBR Green I")) {
			return 1 + "";
		} else if (passReferenceString.equals("HEX")
				|| passReferenceString.equals("JOE")
				|| passReferenceString.equals("CY3")
				|| passReferenceString.equals("TET")) {

			return 2 + "";
		} else if (passReferenceString.equals("ROX")
				|| passReferenceString.equals("TEXAS-RED")) {
			return 3 + "";
		} else if (passReferenceString.equals("CY5")) {
			return 4 + "";
		} else {
			return null;
		}
	}
}
